package com.specialtreasure.freightdepot.dialog;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.app.core.config.Constants;
import com.app.core.config.HttpApi;
import com.app.core.config.MyApp;
import com.app.core.util.UserUtils;
import com.app.core.dialog.BaseDialogFragment;
import com.specialtreasure.freightdepot.R;
import com.specialtreasure.freightdepot.model.BaseModel;
import com.vondear.rxtools.RxKeyboardUtils;
import com.yanzhenjie.httpmodule.http.CallServer;
import com.yanzhenjie.httpmodule.http.Result;
import com.yanzhenjie.httpmodule.http.StringRequest;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.CacheMode;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.SimpleResponseListener;

import org.simple.eventbus.EventBus;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2017/8/21 0021.
 * 信息管理确认弹出界面
 */

public class SureDialogFragment extends BaseDialogFragment implements View.OnClickListener {

    private EditText et_phone;
    private EditText et_goods_cost;
    private EditText et_information_fees;
    private Button btn_sure;
    private Button btn_cancel;
    private ConfirmImpl confirmImpl;
    private Integer itemId;


    public interface ConfirmImpl {
        void btnSure(String phone, String goodsCost, String informationFees);
    }


    public void setConfirmImpl(ConfirmImpl confirmImpl) {
        this.confirmImpl = confirmImpl;
    }



    public static SureDialogFragment newInstance(Integer itemId) {
        SureDialogFragment dialogFragment = new SureDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("itemId",itemId);
        dialogFragment.setArguments(bundle);
        return dialogFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        itemId=getArguments().getInt("itemId");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_order_sure, null);
        outsideDissmiss();
        initView(view);
        return view;
    }


    private void initView(View view) {
        et_phone = (EditText) view.findViewById(R.id.et_phone);
        et_goods_cost = (EditText) view.findViewById(R.id.et_goods_cost);
        et_information_fees = (EditText) view.findViewById(R.id.et_information_fees);
        btn_sure = (Button) view.findViewById(R.id.btn_sure);
        btn_sure.setOnClickListener(this);
        btn_cancel = (Button) view.findViewById(R.id.btn_cancel);
        btn_cancel.setOnClickListener(this);

        //自动弹出输入法
        et_phone.setFocusableInTouchMode(true);
        et_phone.requestFocus();
        et_phone.setFocusable(true);
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                RxKeyboardUtils.showSoftInput(getActivity(),et_phone);
            }
        }, 200);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_sure:
                submit();
                break;
            case R.id.btn_cancel:
                dismissAllowingStateLoss();
                break;
        }

    }



    /**
     * 点击外部不消失
     * 点击返回键不消失
     */
    private void outsideDissmiss() {
        setStyle(STYLE_NORMAL, R.style.commonDialog);
        // 点击外部不消失
        getDialog().setCanceledOnTouchOutside(false);
        //点击返回键不消失，需要监听OnKeyListener:
        getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    return true;
                }
                return false;
            }
        });

    }


    private void submit() {
        // validate
        String phone = et_phone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(getContext(), "请输入接单司机手机号", Toast.LENGTH_SHORT).show();
            return;
        }

        showDialog(Constants.LOADING);
        // TODO validate success, do something

        getData();
    }


    private void getData() {
        String url = Constants.HTTP_URL + HttpApi.SUBMIT;
        StringRequest request = new StringRequest(url, RequestMethod.POST);
        request.add("token", UserUtils.getToken());
        request.add("itemId", itemId);
        request.add("cuserPhone", et_phone.getText().toString().trim());
        request.add("transCharge", et_goods_cost.getText().toString().trim());
        request.add("itemCharge", et_information_fees.getText().toString().trim());

        request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK);


        CallServer.getInstance().request(Constants.ZERO, request, new SimpleResponseListener<Result<String>>() {
            @Override
            public void onSucceed(int what, Response<Result<String>> response) {
                super.onSucceed(what, response);
                closeDialog();

                String result = response.get().getResult();
                Logger.e("请求成功：" + result);
                BaseModel baseModel = JSON.parseObject(result, BaseModel.class);
                if (baseModel != null) {
                    Integer status = baseModel.getStatus();
                    String msg = baseModel.getMsg();
                    if (status != null && status == 0) {
                        EventBus.getDefault().post(new BaseModel(),Constants.UPDATEPUBLIC);
                        Toast.makeText(MyApp.getInstance(), "提交成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MyApp.getInstance(), msg, Toast.LENGTH_SHORT).show();
                    }
                }

                dismissAllowingStateLoss();

            }
        });
    }



//    public ConfirmImpl getSureDialogListener() {
//        return getDialogListener(ConfirmImpl.class);
//    }

}
